<template>
    <van-nav-bar title="协议详情" left-text="返回" left-arrow @click-left="router.back()" @click-right="downloadAsPDF"
        right-text="协议下载" :fixed="true" />
    <div class="pet-adoption-agreement" id="petAdoptionAgreement" ref="content">
        <h2>宠物领养协议</h2>

        <div class="agreement-section">
            <h3>甲方（送养人）</h3>
            <p>姓名：{{ state.adoptionAgreement?.senderName }}</p>
            <p>联系电话：{{ state.adoptionAgreement?.senderPhone }}</p>
        </div>

        <div class="agreement-section">
            <h3>乙方（领养人）</h3>
            <p>姓名：{{ state.adoptionAgreement?.receiverName }}</p>
            <p>联系电话：{{ state.adoptionAgreement?.receiverPhone }}</p>
        </div>

        <div class="agreement-section">
            <h3>领养宠物基本情况</h3>
            <p>名称：{{ state.adoptionAgreement?.pet_name }}</p>
            <p>性别：{{ state.adoptionAgreement?.petGender == 'male' ? '公' : '母' }}</p>
            <p>年龄：{{ state.adoptionAgreement?.petAge }}</p>

        </div>

        <div class="agreement-section">
            <h3>领养费用</h3>
            <p>甲方无偿将上述宠物交由乙方领养，乙方自愿承担宠物日后所需的各项生活、医疗支出。</p>
        </div>

        <div class="agreement-section">
            <h3>甲方权利义务</h3>
            <ul>
                <li>甲方保证该宠物在领养之时健康状况良好，无重大健康隐患。</li>
                <li>甲方有权了解乙方领养条件及领养后的饲养情况，并有权提出合理的建议和要求。</li>
            </ul>
        </div>

        <div class="agreement-section">
            <h3>乙方权利义务</h3>
            <ul>
                <li>乙方承诺为宠物提供科学、健康、合适的饲养环境，给予宠物充分的关心和爱护，保证提供宠物所需的全部食物与医疗条件，不得虐待宠物。</li>
                <li>乙方在领养宠物后，不得随意转让、遗弃宠物。如因特殊原因无法继续饲养，需提前与甲方沟通，并寻找合适的领养人。</li>
                <li>乙方应定期向甲方反馈宠物的饲养情况，包括宠物的健康状况、生活习性等。</li>
            </ul>
        </div>

        <div class="agreement-section">
            <h3>违约责任</h3>
            <p>如乙方违反本协议约定，甲方有权要求乙方立即改正，并有权收回宠物。</p>
            <p>若因乙方原因导致宠物死亡、丢失或遭受虐待，乙方应承担相应的法律责任。</p>
        </div>

        <div class="agreement-section">
            <h3>争议解决</h3>
            <p>双方在履行本协议过程中如发生争议，应首先通过友好协商解决；协商不成的，任何一方均有权向甲方所在地人民法院提起诉讼。</p>
        </div>

        <div class="agreement-section">
            <h3>其他</h3>
            <p>本协议一式两份，甲乙双方各执一份，自双方签字或盖章之日起生效。</p>
            <p>本协议未尽事宜，可由双方另行协商补充。</p>
        </div>
        <div class="signature" v-if="state.showadapt_sign">
            <h3>领养者签名</h3>
            <img :src="state.adoptionAgreement.adapt_sign" v-if="state.adoptionAgreement.adapt_sign" alt="" class="img">
            <van-signature pen-color="#ff0000" v-else @submit="submit" />
        </div>
        <div class="signature" v-if="state.showsender_sign">
            <h3>送养者签名</h3>
            <img :src="state.adoptionAgreement.sender_sign" v-if="state.adoptionAgreement.sender_sign" alt=""
                class="img">
            <van-signature pen-color="#ff0000" @submit="submit" v-else />
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive } from 'vue';
import { queryAgreementDetail, updateSign } from '@/api/index'
import router from '@/router';
import { userStore } from '@/store'
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
const content = ref<string>('')
const id = router.currentRoute.value.params.id as string
import html2pdf from 'html2pdf.js';
import { ref } from 'vue';

const PAGE_WIDTH = 210; // A4页面宽度（毫米）
const PAGE_HEIGHT = document.querySelector('#petAdoptionAgreement')?.scrollHeight; // A4页面高度（毫米）
const MARGIN = 15; 

const downloadAsPDF = async () => {
    const element = document.querySelector('#petAdoptionAgreement');
    const doc = new jsPDF('p', 'mm', 'a4'); // 初始化PDF文档
  const pageHeight = doc.internal.pageSize.getHeight(); // 获取PDF页面高度
  const margin = 10; // 页面边距
  let y = margin; // 当前Y坐标
  let page = 1; // 当前页数

  // 将HTML内容分块处理
  const chunks = splitContentIntoChunks(element, pageHeight - 2 * margin);

  // 遍历每一块内容并添加到PDF
  for (let chunk of chunks) {
    if (y + chunk.height > pageHeight - margin) {
      doc.addPage(); // 添加新页面
      y = margin; // 重置Y坐标
      page++;
    }

    // 使用html2canvas将当前块转换为图片并添加到PDF
    html2canvas(chunk.element, {
  width: bbox.width,
  height: bbox.height,
  windowWidth: doc.internal.pageSize.getWidth(),
  windowHeight: doc.internal.pageSize.getHeight(),
  x: 0,
  y: 0,
  scale: 2, // 可调整清晰度
}).then(tempCanvas => {
  tempCtx.drawImage(tempCanvas, 0, 0, bbox.width, bbox.height);
  const imgData = tempCanvas.toDataURL('image/png');
  doc.addImage(imgData, 'PNG', margin, y, chunk.width / 2, chunk.height / 2); // 注意：scale=2时，宽度和高度要除以2

  y += chunk.height + margin;
});

    const imgData = canvas.toDataURL('image/png');
    doc.addImage(imgData, 'PNG', margin, y, chunk.width / 2, chunk.height / 2); // 注意：scale=2时，宽度和高度要除以2

    y += chunk.height + margin;
  }

  doc.save('output.pdf');
}

const splitContentIntoChunks=(element, maxHeight)=> {
  const chunks = [];
  let currentChunk = {
    element: document.createElement('div'),
    height: 0,
  };

  const originalChildren = Array.from(element.children);
  for (let child of originalChildren) {
    currentChunk.element.appendChild(child.cloneNode(true));

    // 计算当前块的高度
    const tempCanvas = document.createElement('canvas');
    const ctx = tempCanvas.getContext('2d') as CanvasRenderingContext2D;
    const bbox = child.getBoundingClientRect();
    tempCanvas.width = bbox.width;
    tempCanvas.height = bbox.height;
    ctx.drawImage(child, 0, 0, bbox.width, bbox.height);
    currentChunk.height = ctx.canvas.height;

    if (currentChunk.height > maxHeight) {
      // 如果当前块太高，将最后一个子元素移回原处，作为下一个块的开始
      currentChunk.element.removeChild(currentChunk.element.lastChild);
      chunks.push(currentChunk);
      currentChunk = {
        element: document.createElement('div'),
        height: 0,
      };
      currentChunk.element.appendChild(child.cloneNode(true));
    }
  }

  // 添加最后一个块
  if (currentChunk.element.children.length > 0) {
    chunks.push(currentChunk);
  }

  return chunks;
}

let state = reactive({
    adoptionAgreement: {},
    showadapt_sign: false,
    showsender_sign: false
})

onMounted(() => {
    init()
})

const init = () => {
    queryAgreementDetail(id).then((res: any) => {
        if (res.code == 200) {
            state.adoptionAgreement = res.data
            if (state.adoptionAgreement.adapt_sign || state.adoptionAgreement.adapt_id == userStore().userInfo.user_id) {
                state.showadapt_sign = true
            }
            if (state.adoptionAgreement.sender_sign || state.adoptionAgreement.sender_id == userStore().userInfo.user_id) {
                state.showsender_sign = true
            }
        }
    })
}
const submit = (e) => {
    let type = state.adoptionAgreement.adapt_id == userStore().userInfo.user_id ? 'adapt_sign' : 'sender_sign'
    updateSign(e.image, type, state.adoptionAgreement.agreement_id).then(res => {
        if (res.code == 200) {
            init()
        }
    })
}
</script>

<style scoped lang="less">
.pet-adoption-agreement {
    /* 添加你的样式 */
    position: absolute;
    top: 30px;
    box-sizing: border-box;
    padding: 15px;
    overflow: auto;
}

.agreement-section {
    margin-bottom: 20px;
}

.agreement-section h3 {
    margin-bottom: 10px;
}

.signature {
    width: 100%;
    height: auto;

    .img {
        width: 100%;
        height: 100%;
    }
}

/* 你可以根据需要添加更多样式 */
</style>